import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:video_player/video_player.dart';

class VideoWidget extends StatefulWidget {
  dynamic data;
  late _VideoWidgetState _videoWidgetState;
  VideoWidget(this.data, {super.key});

  @override
  State<VideoWidget> createState() {
    _videoWidgetState = _VideoWidgetState();
    return _videoWidgetState;
  }

  void pause() {
    _videoWidgetState.pause();
  }
}

class _VideoWidgetState extends State<VideoWidget>
    with SingleTickerProviderStateMixin {
  /// 会重复播放的控制器
  late final AnimationController _repeatController;

  /// 线性动画
  late final Animation<double> _animation;
  late VideoPlayerController _controller;

  bool init = false;
  @override
  void initState() {
    super.initState();
    if (!init) {
      /// 动画持续时间是 3秒，此处的this指 TickerProviderStateMixin
      _repeatController = AnimationController(
        duration: const Duration(seconds: 10),
        vsync: this,
      )..repeat(); // 设置动画重复播放

      // 创建一个从0到360弧度的补间动画 v * 2 * π
      _animation = Tween<double>(begin: 0, end: 1).animate(_repeatController);

      String url = widget.data["video"]["play_addr"]["url_list"]
          [widget.data["video"]["play_addr"]["url_list"].length - 1];
      _controller = VideoPlayerController.network(url);

      _controller.addListener(() {
        setState(() {});
      });
      _controller.setLooping(true);
      _controller.initialize().then((_) => setState(() {}));
      _controller.play();
      init = true;
    }
  }

  @override
  void dispose() {
    _controller.pause();
    _repeatController.dispose();
    _controller.dispose();
    init = false;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Column(
          children: [
            Expanded(
              flex: 1,
              child: Center(
                child: AspectRatio(
                  aspectRatio: _controller.value.aspectRatio,
                  child: Stack(
                    alignment: Alignment.bottomCenter,
                    children: <Widget>[
                      VideoPlayer(_controller),
                      _ControlsOverlay(controller: _controller),
                    ],
                  ),
                ),
              ),
            ),
            VideoProgressIndicator(
              _controller,
              allowScrubbing: true,
              colors: VideoProgressColors(
                  playedColor: Colors.white,
                  bufferedColor: Colors.white.withOpacity(0.4),
                  backgroundColor: Colors.white.withOpacity(0.1)),
            ),
          ],
        ),
        _buildRightBottons(),
        Positioned(
          left: 0,
          right: 60,
          bottom: 0,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "@" + widget.data["author"]["nickname"],
                  textAlign: TextAlign.left,
                  style: const TextStyle(color: Colors.white, fontSize: 18),
                ),
                Text(widget.data["desc"],
                    textAlign: TextAlign.left,
                    style: const TextStyle(color: Colors.white, fontSize: 16))
              ],
            ),
          ),
        )
      ],
    );
  }

  Positioned _buildRightBottons() {
    return Positioned(
      right: 10,
      bottom: 0,
      child: Column(
        children: [
          SizedBox(
            height: 58,
            child: Stack(
              children: [
                Container(
                  width: 50,
                  height: 50,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(50),
                      border: Border.all(width: 2, color: Colors.white)),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(50),
                    child: Image.network(
                        widget.data['author']["avatar_thumb"]["url_list"][0]),
                  ),
                ),
                Positioned(
                  bottom: 0,
                  right: 0,
                  left: 0,
                  child: Center(
                    child: Container(
                      padding: const EdgeInsets.all(2),
                      decoration: BoxDecoration(
                          color: const Color.fromRGBO(245, 49, 85, 1),
                          borderRadius: BorderRadius.circular(20)),
                      child: const Icon(
                        Icons.add,
                        size: 16,
                        color: Colors.white,
                      ),
                    ),
                  ),
                )
              ],
            ),
          ),
          _buildRightButtonItem("assets/svg/love.svg",
              widget.data["statistics"]["digg_count"].toString()),
          _buildRightButtonItem("assets/svg/msg.svg",
              widget.data["statistics"]["comment_count"].toString()),
          _buildRightButtonItem("assets/svg/colletcion.svg",
              widget.data["statistics"]["collect_count"].toString()),
          _buildRightButtonItem("assets/svg/share.svg",
              widget.data["statistics"]["share_count"].toString()),
          Container(
            margin: EdgeInsets.only(top: 30, bottom: 20),
            width: 50,
            height: 50,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(50),
                border: Border.all(width: 2, color: Colors.white)),
            child: RotationTransition(
              turns: _animation,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(50),
                child: Image.network(
                    widget.data['author']["avatar_thumb"]["url_list"][0]),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Container _buildRightButtonItem(String path, String text) {
    return Container(
      margin: const EdgeInsets.only(top: 30),
      child: Column(
        children: [
          SvgPicture.asset(path),
          const SizedBox(
            height: 8,
          ),
          Text(
            text,
            style: const TextStyle(color: Colors.white),
          )
        ],
      ),
    );
  }

  void pause() {
    if (_controller.value.isPlaying) _controller.pause();
  }
}

class _ControlsOverlay extends StatelessWidget {
  const _ControlsOverlay({Key? key, required this.controller})
      : super(key: key);

  final VideoPlayerController controller;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        AnimatedSwitcher(
          duration: const Duration(milliseconds: 50),
          reverseDuration: const Duration(milliseconds: 200),
          child: controller.value.isPlaying
              ? const SizedBox.shrink()
              : Center(
                  child: Container(
                      margin: EdgeInsets.only(left: 16),
                      width: 70,
                      height: 70,
                      alignment: Alignment.center,
                      child: SvgPicture.asset(
                        "assets/svg/play.svg",
                        color: Colors.white.withOpacity(0.6),
                      )),
                ),
        ),
        GestureDetector(
          onTap: () {
            controller.value.isPlaying ? controller.pause() : controller.play();
          },
        ),
      ],
    );
  }
}
